package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.DefTeamMember;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.domain.dto.AddDefTeamMemberDTO;
import com.ruoyi.system.domain.dto.DefTeamMemberImportDTO;
import com.ruoyi.system.domain.dto.UserWithDrillDTO;
import com.ruoyi.system.domain.vo.TeamUserDetailVO;
import com.ruoyi.system.domain.vo.UserNoRoleVO;
import com.ruoyi.system.domain.vo.UserWithDrillVO;
import com.ruoyi.system.mapper.DefTeamMemberMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.IDefTeamMemberService;
import com.ruoyi.system.service.ISysUserService;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 队伍队员关系Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-10-09
 */
@Service
public class DefTeamMemberServiceImpl implements IDefTeamMemberService 
{
    private static final Logger log = LoggerFactory.getLogger(DefTeamMemberServiceImpl.class);
    @Autowired
    private DefTeamMemberMapper defTeamMemberMapper;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    /**
     * 查询队伍队员关系
     * 
     * @param teamId 队伍队员关系主键
     * @return 队伍队员关系
     */
    @Override
    public DefTeamMember selectDefTeamMemberByTeamId(Integer teamId)
    {
        return defTeamMemberMapper.selectDefTeamMemberByTeamId(teamId);
    }

    /**
     * 查询队伍队员关系列表
     * 
     * @param defTeamMember 队伍队员关系
     * @return 队伍队员关系
     */
    @Override
    public List<DefTeamMember> selectDefTeamMemberList(DefTeamMember defTeamMember)
    {
        return defTeamMemberMapper.selectDefTeamMemberList(defTeamMember);
    }

    /**
     * 新增队伍队员关系
     * 
     * @param defTeamMember 队伍队员关系
     * @return 结果
     */
    @Override
    @Transactional
    public int insertDefTeamMember(AddDefTeamMemberDTO DTO)
    {

        Integer drillId = SecurityUtils.getLoginUser().getDrillId();
        // 判断用户是否存在
        SysUser sysUser = userService.selectUserByUserName(DTO.getPhonenumber());
        int userId = 0;
        if (sysUser == null) {

            SysUser newUser = new SysUser();
            newUser.setNickName(DTO.getNickName());
            newUser.setUserName(DTO.getPhonenumber());
            newUser.setPhonenumber(DTO.getPhonenumber());
            newUser.setRoleId(DTO.getRoleId());
            newUser.setPassword(SecurityUtils.encryptPassword(DTO.getPhonenumber().substring(DTO.getPhonenumber().length() - 6)));
            // 新增用户信息
            userService.insertUser(newUser);
            // 新增用户与角色管理
            userService.insertUserRole(newUser);
            userId = Math.toIntExact(newUser.getUserId());
        } else {
            userId = Math.toIntExact(sysUser.getUserId());
        }

        UserWithDrillDTO userWithDrillDTO = new UserWithDrillDTO();
        userWithDrillDTO.setUserId(userId);
        userWithDrillDTO.setDrillId(drillId);
        userWithDrillDTO.setRoleId(Math.toIntExact(DTO.getRoleId()));

        List<UserWithDrillVO> userWithDrillVOS = userWithDrill(userWithDrillDTO);
        if (CollectionUtils.isNotEmpty(userWithDrillVOS)) {
            UserWithDrillVO userWithDrillVO = userWithDrillVOS.get(0);
            String drillName = userWithDrillVO.getDrillName();
            String userName = userWithDrillVO.getUserName();
            String teamName = userWithDrillVO.getTeamName();
            throw new RuntimeException(
                    "新增队伍队员关系失败,该用户已存在队伍：" + teamName + ",队伍队员：" + userName + ",队伍名称：" + drillName);
        }
        DefTeamMember defTeamMember = new DefTeamMember();
        defTeamMember.setDrillId(drillId);
        defTeamMember.setTeamUser(userId);
        defTeamMember.setTeamId(DTO.getTeamId());
        defTeamMember.setTeamUser(userId);
        defTeamMember.setRoleId(DTO.getRoleId());
        defTeamMember.setRemark(DTO.getRemark());
        if (DTO.getRoleId() != null) {
            userRoleMapper.deleteUserRoleByUserId((long) userId);
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
                SysUserRole ur = new SysUserRole();
                ur.setUserId((long) userId);
                ur.setRoleId(DTO.getRoleId());
                list.add(ur);
            userRoleMapper.batchUserRole(list);
        }
        return defTeamMemberMapper.insertDefTeamMember(defTeamMember);
    }

    /**
     * 修改队伍队员关系
     * 
     * @param defTeamMember 队伍队员关系
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDefTeamMember(AddDefTeamMemberDTO dto)
    {

        Integer drillId = SecurityUtils.getLoginUser().getDrillId();
        Long userId = dto.getUserId();
        SysUser sysUser = userService.selectUserById(userId);
        sysUser.setNickName(dto.getNickName());
        sysUser.setUserName(dto.getPhonenumber());
        sysUser.setPhonenumber(dto.getPhonenumber());
        sysUser.setRemark(dto.getRemark());

        userService.updateUser(sysUser);

        defTeamMemberMapper.deleteDefTeamMemberByUserId(Math.toIntExact(userId), drillId);
        DefTeamMember defTeamMember = new DefTeamMember();
        defTeamMember.setTeamId(dto.getTeamId());
        defTeamMember.setDrillId(drillId);
        defTeamMember.setTeamUser(Math.toIntExact(dto.getUserId()));
        defTeamMember.setRoleId(dto.getRoleId());
        if (dto.getRoleId() != null) {
            userRoleMapper.deleteUserRoleByUserId(userId);
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            SysUserRole ur = new SysUserRole();
            ur.setUserId(userId);
            ur.setRoleId(dto.getRoleId());
            list.add(ur);
            userRoleMapper.batchUserRole(list);
        }
        return defTeamMemberMapper.insertDefTeamMember(defTeamMember);
    }

    /**
     * 批量删除队伍队员关系
     * 
     * @param teamIds 需要删除的队伍队员关系主键
     * @return 结果
     */
    @Override
    public int deleteDefTeamMemberByTeamIds(Integer[] teamIds)
    {
        return defTeamMemberMapper.deleteDefTeamMemberByTeamIds(teamIds);
    }

    /**
     * 删除队伍队员关系信息
     * 
     * @param teamId 队伍队员关系主键
     * @return 结果
     */
    @Override
    public int deleteDefTeamMemberByTeamId(Integer teamId)
    {
        return defTeamMemberMapper.deleteDefTeamMemberByTeamId(teamId);
    }

    @Override
    public List<UserWithDrillVO> userWithDrill(UserWithDrillDTO defTeamMember) {
        Integer drillId = SecurityUtils.getLoginUser().getDrillId();
        defTeamMember.setDrillId(drillId);
        return defTeamMemberMapper.userWithDrill(defTeamMember);
    }

    @Override
    public TeamUserDetailVO teamUserDetail(Long userId) {
        Integer drillId = SecurityUtils.getLoginUser().getDrillId();
        TeamUserDetailVO  vo= defTeamMemberMapper.teamUserDetail(userId, drillId);
        return null;
    }

    @Override
    @Transactional
    public String importData(List<DefTeamMemberImportDTO> userList, Long roleId) {

        int successCount = 0;
        int failureCount = 0;
        StringBuilder resultMessage = new StringBuilder();

        for (DefTeamMemberImportDTO dto : userList) {
            try {
                // 获取当前登录用户的 drillId
                Integer drillId = SecurityUtils.getLoginUser().getDrillId();

                // 查询是否已有用户
                SysUser sysUser = userService.selectUserByUserName(dto.getPhonenumber());
                int userId = 0;
                if (sysUser == null) {
                    // 创建新用户
                    SysUser newUser = new SysUser();
                    newUser.setNickName(dto.getNickName());
                    newUser.setUserName(dto.getPhonenumber());
                    newUser.setPhonenumber(dto.getPhonenumber());
                    // 使用电话号码的后6位作为默认密码
                    newUser.setPassword(SecurityUtils.encryptPassword(dto.getPhonenumber().substring(dto.getPhonenumber().length() - 6)));
                    // 新增用户
                    userService.insertUser(newUser);
                    // 角色绑定
                    userService.insertUserRole(newUser);
                    userId = Math.toIntExact(newUser.getUserId());
                } else {
                    userId = Math.toIntExact(sysUser.getUserId());
                }
                if (roleId != null) {
                    userRoleMapper.deleteUserRoleByUserId((long) userId);
                    // 新增用户与角色管理
                    List<SysUserRole> list = new ArrayList<SysUserRole>();
                    SysUserRole ur = new SysUserRole();
                    ur.setUserId((long) userId);
                    ur.setRoleId(roleId);
                    list.add(ur);
                    userRoleMapper.batchUserRole(list);
                }
                // 检查该用户是否已存在于当前队伍
                UserWithDrillDTO userWithDrillDTO = new UserWithDrillDTO();
                userWithDrillDTO.setUserId(userId);
                userWithDrillDTO.setDrillId(drillId);
                // 检查是否有相同的用户已经在该演练中
                List<UserWithDrillVO> userWithDrillVOS = userWithDrill(userWithDrillDTO);
                if (CollectionUtils.isNotEmpty(userWithDrillVOS)) {
                    UserWithDrillVO userWithDrillVO = userWithDrillVOS.get(0);
                    // 记录已存在的用户信息
                    String drillName = userWithDrillVO.getDrillName();
                    String userName = userWithDrillVO.getUserName();
                    String teamName = userWithDrillVO.getTeamName();
                    resultMessage.append("导入失败, 用户 ").append(userName)
                            .append(" 已存在于队伍: ").append(teamName)
                            .append(", 演练名称: ").append(drillName).append("\n");
                    failureCount++;
                    continue;
                }

                // 如果不存在，插入队伍成员关系
                DefTeamMember defTeamMember = new DefTeamMember();
                defTeamMember.setDrillId(drillId);
                defTeamMember.setTeamUser(userId);
                defTeamMember.setRoleId(roleId);
                defTeamMember.setRemark("导入的成员");

                // 插入队伍成员信息
                defTeamMemberMapper.insertDefTeamMember(defTeamMember);

                successCount++;
            } catch (Exception e) {
                failureCount++;
                resultMessage.append("导入失败: ").append(e.getMessage()).append("\n");
                throw new RuntimeException(resultMessage.toString());
            }
        }

        resultMessage.append("导入完成, 成功: ").append(successCount).append(" 条, 失败: ").append(failureCount).append(" 条");
        return resultMessage.toString();
    }

    @Override
    public List<UserNoRoleVO> userNoRole() {
        Integer drillId = SecurityUtils.getLoginUser().getDrillId();

        return defTeamMemberMapper.userNoRole(drillId);
    }

    @Override
    public int deleteDefTeamMemberByUserId(Integer userId) {
        Integer drillId = SecurityUtils.getLoginUser().getDrillId();
       return defTeamMemberMapper.deleteDefTeamMemberByUserId(userId, drillId);
    }
}
